WinForm 接收串口消息在UI显示接收串口消息,显示到UI的WinForm,基于事件驱动。 //初始化串口
SerialPort sp = new SerialPort("COM2",9600,Parity.None,8,StopBits.One);
private void Form1_Load(object sender, EventArgs e)
{
try
{
sp.DataReceived = dataRec; //接收事件
sp.ReceivedBytesThreshold = 1; //接收到1个字节就触发
sp.Encoding = Encoding.Default; //设置编码,防止乱码
sp.Open();
}catch
{
MessageBox.Show("打开端口错误");
}
}
private void dataRec(object sender, SerialDataReceivedEventArgs e)
{
string msg = string.Empty;
//循环读取缓冲区,把所有的都读出来
//也可以用延时读取
while (sp.BytesToRead>0)
{
msg = sp.ReadExisting();
}
//更新UI
this.BeginInvoke((EventHandler)delegate
{
label1.Text = msg Environment.NewLine;
}
);
}
.
├── ComPortEvent3
│ ├── ComPortEvent3.csproj
│ ├── Form1.Designer.cs
│ ├── Form1.cs
│ ├── Form1.resx
│ ├── Program.cs
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ ├── Resources.Designer.cs
│ │ ├── Resources.resx
│ │ ├── Settings.Designer.cs
│ │ └── Settings.settings
│ ├── bin
│ │ └── Debug
│ │ ├── ComPortEvent3.exe
│ │ ├── ComPortEvent3.pdb
│ │ ├── ComPortEvent3.vshost.exe
│ │ └── ComPortEvent3.vshost.exe.manifest
│ └── obj
│ └── Debug
│ ├── ComPortEvent3.Form1.resources
│ ├── ComPortEvent3.Properties.Resources.resources
│ ├── ComPortEvent3.csproj.FileListAbsolute.txt
│ ├── ComPortEvent3.csproj.GenerateResource.Cache
│ ├── ComPortEvent3.csprojResolveAssemblyReference.cache
│ ├── ComPortEvent3.exe
│ ├── ComPortEvent3.pdb
│ ├── DesignTimeResolveAssemblyReferences.cache
│ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ └── TempPE
├── ComPortEvent3.sln
└── 找例子网_ComPortEvent3.zip
7 directories, 25 files
评论